package cn.anlab.anappframe.service;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.anlab.anappframe.R;
import cn.anlab.anappframe.demo.activity.ChatDemoActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class CoreService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		Log.i("anlog", "onBind...");
		return null;
	}
	
	@Override
	public void onCreate() {
		Log.i("anlog", "onCreate...");
		super.onCreate();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		Log.i("anlog", "onStart...");
		super.onStart(intent, startId);
		
		ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
		executorService.scheduleAtFixedRate(task, 1, 20, TimeUnit.SECONDS);
	}
	
	@Override
	public void onDestroy() {
		Log.i("anlog", "onDestroy...");
		super.onDestroy();
	}

	private Runnable task = new Runnable() {
		@Override
		public void run() {
			handler.sendEmptyMessage(100);
		}
	};
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			Log.i("anlog", new Date().toString());
			
			//设置通知显示
			int icon = R.drawable.app_icon;
			String text = "移动互联网开发框架";					//通知到时，在手机顶部显示的该字，
			long when = System.currentTimeMillis();			//通知行显示的时间
			Notification notification = new Notification(icon, text, when);
			
			//设置通知点击事件
			String contentTitle = "开发框架";				//通知行的标题
			String contentText = "你有新消息！";		//通知行的内容
			Intent intent = new Intent(CoreService.this, ChatDemoActivity.class);
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			//PendingIntent参数说明：
			//FLAG_UPDATE_CURRENT 下次通知来时，能更新通知行的内容
			//FLAG_ONE_SHOT同一消息只使用一次，再次点击时，没响应了
			//
			PendingIntent contentIntent = PendingIntent.getActivity(CoreService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT ); 
			notification.setLatestEventInfo(CoreService.this, contentTitle, contentText, contentIntent);
			
			//发送通知
			NotificationManager notificationMng = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
			notificationMng.notify(2002, notification);
			
		};
	};
	
	
}
